
<template>

  <div class="singer">
    <list-view :data="singers"
               @select="selectSinger">
    </list-view>
    <router-view></router-view>
  </div>
</template>

<script>
import { getSingerList } from "@/api/singer";
import { ERR_OK } from "@/api/config";
import Singer from "common/js/singer";
import listView from "base/listview/listview";
import { mapMutations } from "vuex";
const HOT_NAME = "热门";
const HOT_SINGER_LEN = 10;
export default {
  data () {
    return {
      singers: []
    }
  },
  created () {
    this._getSingerList();
  },
  methods: {
    selectSinger (singer) {
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer);
    },
    async _getSingerList () {
      let res = await getSingerList();
      if (res.code === ERR_OK) {
        this.singers = this._normalizeSinger(res.data.list);
      }
    },
    _normalizeSinger (list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      for (let index of Object.keys(list)) {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer(list[index]))
        }
        const key = list[index].Findex;
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer(list[index]))
      }

      // 得到有序列表
      let hot = []
      let others = []

      for (let key in map) {

        let value = map[key]
        if (value.title.match(/[a-zA-Z]/)) {
          others.push(value)
        } else if (value.title === HOT_NAME) {
          hot.push(value)
        }
      }


      others.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(others)
    },
    ...mapMutations({
      setSinger:"SET_SINGER"
    })
  },
  components: {
    listView
  }
}
</script>

<style scoped>
.singer {
  position: fixed;
  top: 176px;
  bottom: 0;
  width: 100%;
}
</style>
